package com.mec.beans.y2013.util;

import org.apache.log4j.Logger;

/**
 * Utility class for handling file path;
 * @author MEC
 * @since 2013-03-29
 */
public class FilePathUtil {
	private FilePathUtil(){
		
	}
	
	public static FilePathUtil getInstance(){
		return instance;
	}
	
	/**
	 * Wrap the rawPath string with system fileSeparator;
	 * input:
	 * 1, "2013/03/29"
	 * 
	 * output:
	 * 1, "/2013/03/29/" (linux)
	 * 	or "\2013/03/29\" (windows);
	 * 2,
	 * 
	 * That's it.
	 * @param rawPath the raw path string;
	 * @return
	 */
	public String wrapAsFilePath(String rawPath){
		String retval = rawPath;
		
		if(!rawPath.startsWith(sep)){
			retval = sep + retval;
		}
		
		if(!rawPath.endsWith(sep)){
			retval += sep;
		}
		
		return retval;
	}
	
	
	/**
	 * Generate random String from the original file name;
	 * INPUT:
	 * 1, img-1.jpg, 5
	 * 2, /var/www/test_web/uploaded/2013/03/29/img-2.jpg, 15
	 * OUTPUT:
	 * 1, img-1gvmXj.jpg
	 * 2,/var/www/test_web/uploaded/2013/03/29/img-2uwxShJ50g84yeiS.jpg
	 * @param fileName original file name;
	 * @param randSuffixLength length of the random suffix string;
	 * @return
	 */
	public String genRandomFileName(String fileName, int randSuffixLength){
		if(null == fileName){
			fileName = "";
		}
		String retval = "";
		
		int dotIndex = fileName.lastIndexOf('.');
		if( 0 > dotIndex){ // fileName dose not contain "."
			retval = fileName + strUtil.getRandStr(randSuffixLength);
		}else{ // file_name + random_str + file_extension;
			retval = fileName.substring(0, dotIndex) + 
					APPEND_SEP +	// add an underscore here, 2013-03-29;
					strUtil.getRandStr(randSuffixLength) +
					fileName.substring(dotIndex);
 		}
		
		return retval;
	}
	
	private static final String APPEND_SEP = "_";
	private StringUtil strUtil = StringUtil.getInstance();
	private FileUploadUtil upUtil = FileUploadUtil.getInstance();
	private String sep = java.io.File.separator;
	private String randomPattern = "yyyyMMddHHmmss"; // append sdf.format(new Date()) to the file name?
	private static final FilePathUtil instance = new FilePathUtil();
	private static final Logger logger = Logger.getLogger(FilePathUtil.class);
}
